/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package imager;

import coneccion.ConexionBase;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JOptionPane;

/**
 *
 * @author El APRENDIZ www.elaprendiz.net63.net
 */
public class PopupDatos extends javax.swing.JDialog {

    /**
     * Creates new form PopupDatos
     */
    private final String config = System.getProperty("user.dir")+"/data.dat";
    public PopupDatos(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        this.setVisible(false);
        verificarConfiguracion();
       
    }
    
    private void verificarConfiguracion()
    {
        File fconfig = exitsFileConfig(config);
       if(fconfig != null)
       {
            ArrayList rfc = readFileConfig(fconfig);
            if(rfc.size()>0)
            {
                this.txtBd.setText(rfc.get(0).toString());
                this.txtUser.setText(rfc.get(1).toString());
                ConexionBase.setNombreBD(rfc.get(0).toString());
                ConexionBase.setUsuario(rfc.get(1).toString());
                if(rfc.size() > 2)
                {
                   this.pfPass.setText(rfc.get(3).toString()); 
                   ConexionBase.setClave(rfc.get(3).toString());
                }else{
                    this.pfPass.setText("");
                }
                if(ConexionBase.conectar())
                {
                    int op = JOptionPane.showConfirmDialog(this, "El Sistema ha encontrado un archivo de configuracion."
                            + " y los datos son validos.\nRuta del Archivo:"
                            + fconfig.getAbsolutePath()+"\n"
                            + "¿Desea continuar? ", "¿Desea Continuar?", JOptionPane.YES_NO_OPTION);
                    if(op == JOptionPane.OK_OPTION)
                    {
                        iniciaClientes();
                    }else{
                        this.setVisible(true);
                    }
                }else
                {
                    this.setVisible(true);
                }
            }
            
       }else
       {
           this.setVisible(true);
       }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        lbAviso = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtBd = new javax.swing.JTextField();
        bntIngresar = new javax.swing.JButton();
        bntcancelar = new javax.swing.JButton();
        pfPass = new javax.swing.JPasswordField();
        jLabel4 = new javax.swing.JLabel();
        txtUser = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Datos de Coneccion");
        setLocationByPlatform(true);
        setResizable(false);

        jPanel1.setLayout(new java.awt.GridBagLayout());

        lbAviso.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lbAviso.setText("Ingrese Datos de Coneccion:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = 10;
        gridBagConstraints.insets = new java.awt.Insets(4, 0, 0, 0);
        jPanel1.add(lbAviso, gridBagConstraints);

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("Nombre BD:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(4, 8, 0, 0);
        jPanel1.add(jLabel2, gridBagConstraints);

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel3.setText("Contraseña:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(4, 8, 0, 0);
        jPanel1.add(jLabel3, gridBagConstraints);

        txtBd.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtBd.setPreferredSize(new java.awt.Dimension(180, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.insets = new java.awt.Insets(4, 6, 0, 7);
        jPanel1.add(txtBd, gridBagConstraints);

        bntIngresar.setText("Ingresar");
        bntIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntIngresarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(4, 5, 5, 0);
        jPanel1.add(bntIngresar, gridBagConstraints);

        bntcancelar.setText("Cancelar");
        bntcancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntcancelarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(4, 0, 5, 7);
        jPanel1.add(bntcancelar, gridBagConstraints);

        pfPass.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        pfPass.setPreferredSize(new java.awt.Dimension(180, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.insets = new java.awt.Insets(4, 6, 0, 7);
        jPanel1.add(pfPass, gridBagConstraints);

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setText("Usuario:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(4, 8, 0, 0);
        jPanel1.add(jLabel4, gridBagConstraints);

        txtUser.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtUser.setPreferredSize(new java.awt.Dimension(180, 23));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.insets = new java.awt.Insets(4, 6, 0, 7);
        jPanel1.add(txtUser, gridBagConstraints);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bntIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntIngresarActionPerformed
        if(this.txtBd.getText().isEmpty() || this.txtUser.getText().isEmpty())
        {
            int op = JOptionPane.showConfirmDialog(this, "Laa coneccion se realizara con los datos por defecto.\n"
                                            + "¿Desea continuar?", "¿Desea Continuar?", JOptionPane.YES_NO_CANCEL_OPTION);
            if(op == JOptionPane.OK_OPTION)
            {
                if(ConexionBase.conectar())
                {
                  writeFile(config,this.txtBd.getText()+"\n"+this.txtUser.getText()+"\n"+String.valueOf(this.pfPass.getPassword()));
                  iniciaClientes();
                }
                
            }else{
                this.txtBd.requestFocus();
            }
        }else
        {
            ConexionBase.setNombreBD(this.txtBd.getText());
            ConexionBase.setUsuario(this.txtUser.getText());
            if(this.pfPass.getPassword().length>0)
            {
              ConexionBase.setClave(String.valueOf(this.pfPass.getPassword()));  
            }else{
                ConexionBase.setClave("");
            }           
            if(ConexionBase.conectar())
            {
                writeFile(config,this.txtBd.getText()+"\n"+this.txtUser.getText()+"\n"+String.valueOf(this.pfPass.getPassword()));
                iniciaClientes();
            }
        }
    }//GEN-LAST:event_bntIngresarActionPerformed

    private void bntcancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntcancelarActionPerformed
        System.exit(0);
    }//GEN-LAST:event_bntcancelarActionPerformed

    private void iniciaClientes()
    {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LeerClientes().setVisible(true);
            }
        });
        this.dispose();
    }
       
     public  void writeFile(String canonicalFilename, String data)
    {
        try{
              File file = new File (canonicalFilename);
              if(!file.exists()){
                  if(file.createNewFile()){
                         System.out.println(file.getAbsolutePath());                          
                          BufferedWriter out = new BufferedWriter(new FileWriter(file));
                          out.write(data);                          
                          JOptionPane.showMessageDialog(this, "Los datos son correctos.\nConfiguracion guardada en: "+file.getAbsolutePath());
                          out.close();
                       }
                 
            }else
              {
                  BufferedWriter out = new BufferedWriter(new FileWriter(file));
                  out.write(data);
                  out.close();                  
                  JOptionPane.showMessageDialog(this, "Existia una configuracion previa en: "+file.getAbsolutePath()+" pero se reescribio");
                  System.out.println("el archuivo ya existe en: "+file.getAbsolutePath());
            }

            
             
        }catch(IOException io){}
    }

    private File exitsFileConfig(String nomefile)
    {
        File file  =  new File(nomefile);
        if(file.exists())
           return file;
        else
            return null;
    }

   private ArrayList readFileConfig(File file)
   {
      // String data = null;
       ArrayList datos = new ArrayList();
       try{
           
            File fstream = file;
            BufferedReader br = new BufferedReader(new FileReader(fstream));
            String strLine;
            //Leyendo archivo linea por linea
            while ((strLine = br.readLine()) != null)   {             
              //data = strLine;
              datos.add(strLine);
            }
            //cerrando el flujo de entrada
            br.close();
            }catch (Exception e){System.err.println("Error: " + e.getMessage());}
            
                //System.out.println(data);
            
        return datos;
   }
    /**
     * @param args the command line arguments
     */
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bntIngresar;
    private javax.swing.JButton bntcancelar;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lbAviso;
    private javax.swing.JPasswordField pfPass;
    private javax.swing.JTextField txtBd;
    private javax.swing.JTextField txtUser;
    // End of variables declaration//GEN-END:variables
}
